package com.pangolin.pangolinim.ui.activity;

import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.viewpager2.widget.ViewPager2;

import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.net.NetFormat;
import com.pangolin.pangolinim.service.list.ContactList;
import com.pangolin.pangolinim.service.list.SessionList;
import com.pangolin.pangolinim.sqlite.DBContact;
import com.pangolin.pangolinim.sqlite.DBSession;
import com.pangolin.pangolinim.ui.adapter.CommonFragmentPagerAdapter;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.adapter.UISession;
import com.pangolin.pangolinim.ui.base.BaseActivity;
import com.pangolin.pangolinim.ui.base.BaseFragment;
import com.pangolin.pangolinim.ui.fragment.ContactsFragment;
import com.pangolin.pangolinim.ui.fragment.FragmentFactory;
import com.pangolin.pangolinim.ui.fragment.MeFragment;
import com.pangolin.pangolinim.ui.fragment.RecentMessageFragment;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.DateUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.ImageUtil;
import com.pangolin.pangolinim.utils.PopupWindowUtil;
import com.pangolin.pangolinim.utils.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private List<BaseFragment> mFragmentList = new ArrayList<>(3);

    private ImageButton mIbAddMenu;
    private TextView mTvMessageNormal;
    private TextView mTvContactsNormal;
    private TextView mTvMeNormal;
    private TextView mTvMessagePress;
    private TextView mTvMePress;
    private TextView mTvContactsPress;
    private TextView mTvMessageTextNormal;
    private TextView mTvContactsTextNormal;
    private TextView mTvMeTextNormal;
    private TextView mTvMessageTextPress;
    private TextView mTvContactsTextPress;
    private TextView mTvMeTextPress;
    private LinearLayout mLlMessage;
    private LinearLayout mLlContacts;
    private LinearLayout mLlMe;
    private ViewPager2 mVpContent;
    public TextView mTvContactRedDot;
    public TextView mTvMessageRedDot;

    private boolean isFirstRun;

    public UIContact me = new UIContact();

    @Override
    protected void init(){
        String strM = getIntent().getStringExtra("param1");
        UIContact m = GsonUtil.fromJson(strM , UIContact.class);
        me.setUid(m.getUid());
        me.setName(m.getName());
        me.setHeader(m.getHeader());
        File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , me.getHeader());
        if(file.exists() && file.isFile()){
            me.setBitHeader(ImageUtil.getBitmapFromFile(this , file , 120 , 120));
        }
        isFirstRun = true;
    }

    @Override
    protected void initView(){
        mIbAddMenu = findViewById(R.id.ibAddMenu);
        mTvMessageNormal = findViewById(R.id.tvMessageNormal);
        mTvContactsNormal = findViewById(R.id.tvContactsNormal);
        mTvMeNormal = findViewById(R.id.tvMeNormal);
        mTvMessagePress = findViewById(R.id.tvMessagePress);
        mTvMePress = findViewById(R.id.tvMePress);
        mTvContactsPress = findViewById(R.id.tvContactsPress);
        mTvMessageTextNormal = findViewById(R.id.tvMessageTextNormal);
        mTvContactsTextNormal = findViewById(R.id.tvContactsTextNormal);
        mTvMeTextNormal = findViewById(R.id.tvMeTextNormal);
        mTvMessageTextPress = findViewById(R.id.tvMessageTextPress);
        mTvContactsTextPress = findViewById(R.id.tvContactsTextPress);
        mTvMeTextPress = findViewById(R.id.tvMeTextPress);
        mLlMessage = findViewById(R.id.llMessage);
        mLlContacts = findViewById(R.id.llContacts);
        mLlMe = findViewById(R.id.llMe);
        mVpContent = findViewById(R.id.vpContent);
        mTvContactRedDot = findViewById(R.id.tvContactRedDot);
        mTvMessageRedDot = findViewById(R.id.tvMessageRedDot);

        mIbAddMenu.setVisibility(View.VISIBLE);

        //默认选中第一个
        setTransparency();
        mTvMessagePress.getBackground().setAlpha(255);
        mTvMessageTextPress.setTextColor(Color.argb(255, 69, 192, 26));

        //设置ViewPager的最大缓存页面
        //mVpContent.setOffscreenPageLimit(2);

        mFragmentList.add(FragmentFactory.getInstance().getRecentMessageFragment());
        mFragmentList.add(FragmentFactory.getInstance().getContactsFragment());
        mFragmentList.add(FragmentFactory.getInstance().getMeFragment());
        mVpContent.setAdapter(new CommonFragmentPagerAdapter(this, mFragmentList));
    }

    @Override
    protected void initListener(){
        mIbAddMenu.setOnClickListener(v -> {
            //显示或隐藏popupwindow
            View menuView = View.inflate(MainActivity.this, R.layout.menu_main, null);
            PopupWindow popupWindow = PopupWindowUtil.getPopupWindowAtLocation(menuView, getWindow().getDecorView(), Gravity.TOP | Gravity.RIGHT, UIUtil.dip2Px(5), mAppBar.getHeight() + 30);
            menuView.findViewById(R.id.tvHelpFeedback).setOnClickListener(v1 -> {
                //jumpToWebViewActivity(AppConst.WeChatUrl.HELP_FEED_BACK);
                popupWindow.dismiss();
            });
            menuView.findViewById(R.id.tvAddFriend).setOnClickListener(v1 -> {
                jumpToActivity(AddFriendActivity.class , GsonUtil.toJson(me));
                popupWindow.dismiss();
            });
        });
        mLlMessage.setOnClickListener(v -> bottomBtnClick(v));
        mLlContacts.setOnClickListener(v -> bottomBtnClick(v));
        mLlMe.setOnClickListener(v -> bottomBtnClick(v));
        mVpContent.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                //根据ViewPager滑动位置更改透明度
                int diaphaneity_one = (int) (255 * positionOffset);
                int diaphaneity_two = (int) (255 * (1 - positionOffset));
                switch (position) {
                    case 0:
                        mTvMessageNormal.getBackground().setAlpha(diaphaneity_one);
                        mTvMessagePress.getBackground().setAlpha(diaphaneity_two);
                        mTvContactsNormal.getBackground().setAlpha(diaphaneity_two);
                        mTvContactsPress.getBackground().setAlpha(diaphaneity_one);
                        mTvMessageTextNormal.setTextColor(Color.argb(diaphaneity_one, 153, 153, 153));
                        mTvMessageTextPress.setTextColor(Color.argb(diaphaneity_two, 69, 192, 26));
                        mTvContactsTextNormal.setTextColor(Color.argb(diaphaneity_two, 153, 153, 153));
                        mTvContactsTextPress.setTextColor(Color.argb(diaphaneity_one, 69, 192, 26));
                        break;
                    case 1:
                        mTvContactsNormal.getBackground().setAlpha(diaphaneity_one);
                        mTvContactsPress.getBackground().setAlpha(diaphaneity_two);
                        mTvMeNormal.getBackground().setAlpha(diaphaneity_two);
                        mTvMePress.getBackground().setAlpha(diaphaneity_one);
                        mTvContactsTextNormal.setTextColor(Color.argb(diaphaneity_one, 153, 153, 153));
                        mTvContactsTextPress.setTextColor(Color.argb(diaphaneity_two, 69, 192, 26));
                        mTvMeTextNormal.setTextColor(Color.argb(diaphaneity_two, 153, 153, 153));
                        mTvMeTextPress.setTextColor(Color.argb(diaphaneity_one, 69, 192, 26));
                        break;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        /** 发送获取离线消息请求，该操作只在初始化时执行一次 */
        if(isFirstRun){
            Logger.d("请求离线消息");
            Map<String, Object> brocastMap = new HashMap<String, Object>();
            brocastMap.put("type" , BroadcastMsg.DATA_UI_OFFMSG);
            BundleUtil sendBundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
            BroadcastSender(sendBundleUtil.getBundle());
            isFirstRun = false;
        }
    }

    @Override
    protected void CoreMessage(BundleUtil bundleUtil){
        if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_DATA){
            if(bundleUtil.getData() != null){
                Map<String, Object> resMap = bundleUtil.getData();
                if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_CONTACTS){    //联系人列表请求返回
                    if((int)resMap.get("result") == 0){
                        //加载联系人
                        loadContacts((String) resMap.get("contacts"));
//                        /** 发送获取离线消息请求，该操作只在初始化时执行一次 */
//                        if(isFirstRun){
//                            Logger.d("请求离线消息");
//                            Map<String, Object> brocastMap = new HashMap<String, Object>();
//                            brocastMap.put("type" , BroadcastMsg.DATA_UI_OFFMSG);
//                            BundleUtil sendBundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
//                            BroadcastSender(sendBundleUtil.getBundle());
//                            isFirstRun = false;
//                        }
                    }else{
                        UIUtil.showToast(NetFormat.ResMsg((int) resMap.get("result")));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_OFFMSG){
                    if((int)resMap.get("result") == 0){
                        //加载离线消息
                        Logger.d("离线消息获取成功");
                    }else{
                        UIUtil.showToast(NetFormat.ResMsg((int) resMap.get("result")));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_SESSIONS){
                    if((int)resMap.get("result") == 0){
                        //加载最近会话列表
                        loadSessions((String) resMap.get("sessions"));
                    }else{
                        UIUtil.showToast(NetFormat.ResMsg((int) resMap.get("result")));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_MYINFO){
                    me.setUid((int) resMap.get("uid"));
                    me.setName((String) resMap.get("name"));
                    me.setHeader((String) resMap.get("headimg"));
                    File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , me.getHeader());
                    if(file.exists() && file.isFile()){
                        me.setBitHeader(ImageUtil.getBitmapFromFile(this , file , 120 , 120));
                    }
                    //Logger.d("me:%d|%s|%s" , me.getUid() , me.getName() , me.getHeader());
                    loadMyinfo();
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_DOWNPIC){
                    if((int)resMap.get("result") == 0){
                        Logger.d("头像下载完毕"+(String)resMap.get("filename"));
                        if(me.getHeader().equals((String)resMap.get("filename"))){  //自己头像
                            File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , (String)resMap.get("filename"));
                            if(file.exists() && file.isFile()){
                                me.setBitHeader(ImageUtil.getBitmapFromFile(this , file , 120 , 120));
                                loadMyinfo();
                            }else{
                                UIUtil.showToast("头像图片文件丢失，请重新下载");
                            }
                        }
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_CLIMSG){
                    //刷新会话列表
                    UISession session = new UISession();
                    session.setUid((int) resMap.get("uid"));
                    session.setLastmsg((String) resMap.get("context"));
                    session.setLasttime(DateUtil.getWechatTime(((int) resMap.get("time")) * 1000l));
                    session.setMsgtype((int) resMap.get("msgtype"));
                    //Logger.d("%d|%s|%s|%d" , session.getUid() , session.getLastmsg() , session.getLasttime() , session.getMsgtype());
                    mTvMessageRedDot.setVisibility(View.VISIBLE);
                    RecentMessageFragment recentMessageFragment = FragmentFactory.getInstance().getRecentMessageFragment();
                    recentMessageFragment.setSession(session);
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_CLIOPERATE){
                    mTvContactRedDot.setVisibility(View.VISIBLE);
                    ContactsFragment contactsFragment = FragmentFactory.getInstance().getContactsFragment();
                    contactsFragment.setUnread();
                }
            }
        }
    }

    @Override
    protected int provideContentViewId(){
        return R.layout.activity_main;
    }

    /**
     * 把press图片、文字全部隐藏(设置透明度)
     */
    private void setTransparency() {
        mTvMessageNormal.getBackground().setAlpha(255);
        mTvContactsNormal.getBackground().setAlpha(255);
        mTvMeNormal.getBackground().setAlpha(255);
        mTvMessagePress.getBackground().setAlpha(1);
        mTvContactsPress.getBackground().setAlpha(1);
        mTvMePress.getBackground().setAlpha(1);
        mTvMessageTextNormal.setTextColor(Color.argb(255, 153, 153, 153));
        mTvContactsTextNormal.setTextColor(Color.argb(255, 153, 153, 153));
        mTvMeTextNormal.setTextColor(Color.argb(255, 153, 153, 153));
        mTvMessageTextPress.setTextColor(Color.argb(0, 69, 192, 26));
        mTvContactsTextPress.setTextColor(Color.argb(0, 69, 192, 26));
        mTvMeTextPress.setTextColor(Color.argb(0, 69, 192, 26));
    }

    @Override
    protected boolean isToolbarCanBack() {
        return false;
    }

    public void bottomBtnClick(View view) {
        setTransparency();
        switch (view.getId()) {
            case R.id.llMessage:
                mVpContent.setCurrentItem(0, false);
                mTvMessagePress.getBackground().setAlpha(255);
                mTvMessageTextPress.setTextColor(Color.argb(255, 69, 192, 26));
                break;
            case R.id.llContacts:
                mVpContent.setCurrentItem(1, false);
                mTvContactsPress.getBackground().setAlpha(255);
                mTvContactsTextPress.setTextColor(Color.argb(255, 69, 192, 26));
                break;
            case R.id.llMe:
                mVpContent.setCurrentItem(2, false);
                mTvMePress.getBackground().setAlpha(255);
                mTvMeTextPress.setTextColor(Color.argb(255, 69, 192, 26));
                break;
        }
    }

    /**
     * TODO:加载个人信息
     */
    private void loadMyinfo(){
        MeFragment meFragment = FragmentFactory.getInstance().getMeFragment();
        meFragment.setMyInfo(me);
    }

    /**
     * TODO:反序列化联系人数据并加载到UI
     * @param str_contacts 广播数据中序列化成字符串的ContactList类
     */
    private void loadContacts(String str_contacts){
        //反序列化
        ContactList contactList = GsonUtil.fromJson(str_contacts , ContactList.class);
        if(contactList != null){
            List<DBContact> contacts = contactList.get_allcontacts();
//            for (DBContact contact : contacts){
//                Logger.d("contact:%d|%s|%s|%s" , contact.getUid() , contact.getName() , contact.getHeadimg() , contact.getSeckey());
//            }
            ContactsFragment contactsFragment = FragmentFactory.getInstance().getContactsFragment();
            contactsFragment.setContacts(contacts);
        }
    }

    /**
     * TODO:反序列化最近会话数据并加载到UI
     * @param str_sessions 广播数据中序列化成字符串的SessionList类
     */
    private void loadSessions(String str_sessions){
        //反序列化
        SessionList sessionList = GsonUtil.fromJson(str_sessions , SessionList.class);
        if(sessionList != null){
            List<DBSession> sessions = sessionList.get_sessions();
//            for (DBSession session : sessions){
//                Logger.d("session:%d|%s|%s|%d|%s|%d" ,
//                        session.getUid() ,
//                        session.getName() ,
//                        session.getHeadimg() ,
//                        session.getMsgtype() ,
//                        session.getLastmsg() ,
//                        session.getUnread());
//            }
            RecentMessageFragment recentMessageFragment = FragmentFactory.getInstance().getRecentMessageFragment();
            recentMessageFragment.setSessions(sessions);
        }
    }
}